<template>
  <div class="pane-account">
    <el-form :model="account" :rules="accountRules" label-width="60px" size="large" status-icon ref="formRef">
      <el-form-item label="帐号" prop="name">
        <el-input v-model="account.name" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="account.password" show-password />
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
//这里为什么叫加type
import type { FormRules, ElForm } from 'element-plus'
import useLoginStore from '@/store/login/index'

import type { Iaccount } from '@/types'
import { localCache } from '@/utils/storage'

const LOGIN_NAME = 'name'
const LOGIN_PWD = 'password'

const formRef = ref<InstanceType<typeof ElForm>>()

//1.定义表单数据
const account = reactive<Iaccount>({
  //??非空断言
  name: localCache.getStorage('name') ?? '',
  password: localCache.getStorage('password') ?? ''
})

// 2.定义校验规则
const accountRules: FormRules = {
  name: [
    { required: true, message: '必须输入帐号信息~', trigger: 'blur' },
    {
      pattern: /^[a-z0-9]{6,20}$/,
      message: '必须是6~20数字或字母组成~',
      trigger: 'blur'
    }
  ],
  password: [
    { required: true, message: '必须输入密码信息~', trigger: 'blur' },
    {
      pattern: /^[a-z0-9]{3,}$/,
      message: '必须是3位以上数字或字母组成',
      trigger: 'blur'
    }
  ]
}
const loginStore = useLoginStore()
/**
 * 执行登录操作
 */
function loginOpt(isRemPwd: boolean) {
  //在执行登录前做校验
  formRef.value?.validate((valid) => {
    if (valid) {
      // 1.获取用户输入的帐号和密码
      let params = {
        name: account.name,
        password: account.password
      }
      //登录数据保存到pina
      loginStore.loginAccountAction(params).then((res) => {
        //判断是否登录成功，成功后如果勾选了记住密码复选框，才会缓存密码
        if (isRemPwd) {
          localCache.setStorage(LOGIN_NAME, account.name)
          localCache.setStorage(LOGIN_PWD, account.password)
        } else {
          //没有记住密码清空缓存
          localCache.removeStorage(LOGIN_NAME)
          localCache.removeStorage(LOGIN_PWD)
        }
      })
    } else {
      ElMessage.error('Oops, 请您输入正确的格式后再操作~~.')
    }
  })
}

//向父组件暴露子组件的方法
defineExpose({ loginOpt })
</script>

<style lang="less" scoped>
.pane-account {
  color: red;
}
</style>
